import axios from "axios";
import {
  type AxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";
import router from "@/router/index.ts";

// 类型判断
export function typeOf(obj: any) {
  const toString = Object.prototype.toString;
  const map: any = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
    "[object Error]": "error",
  };
  return map[toString.call(obj)];
}

// callApi配置类型
export interface CallApiConfig {
  api: string; // 请求地址 
  method?: string; // 请求方式 
  param?: Record<string, any>; // 请求json参数
  config?: AxiosRequestConfig; // 请求设置
  isApiLogin?: boolean; // 自定义判断标识
}
// 错误信息映射对象
const errorMap: Record<string, string> = {
  "Network Error": "网络异常，请检查设备网络状况",
};

// request 拦截器
let instance = axios.create({
  baseURL: `${window.location.origin}/emer/`,
  timeout: 500 * 1000,
  headers: {
    "Content-Type": "application/json; charset=UTF-8",
  },
});

// request 拦截器
instance.interceptors.request.use(
  (config: any) => {
    config.headers.Authorization = sessionStorage.getItem("token");
    // 对应请求数据做点什么
    if (config.isApiLogin) {
      config.baseURL = `${window.location.origin}/api/`;
    }
    // console.log("request 拦截器", config);
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    Promise.reject(error);
  }
);

// response 拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    console.log("response 拦截器");

    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);


/**
 *
 * @param {string} api 接口名
 * @param {string} param 接口入参
 * @param {string} config 自定义config配置
 */
const callApi = ({
  api,
  param = {},
  config = {},
  isApiLogin = false,
}: CallApiConfig) => {
  config.method = config.method ? config.method : "post";
  Object.assign(config, { url: api, data: param, isApiLogin });

  return instance(config)
    .then((res: any) => {
      if (config.responseType) {
        return res;
      }

      if (res.code == "200") {
        return res;
      }
      return Promise.reject({
        code: res.code,
        message: res.message || res.msg || "请求错误",
      });
    })
    .catch((error) => {
      console.log(error, isApiLogin, "error");
      if (error.message && error.message !='获取用户信息失败！请重新登录！') {
        ElMessage({
          type: "warning",
          message: error.message,
        });
      }
      let message = error.message;
      if (error.message.includes("timeout")) {
        message = "请求时长过长，请耐心等候";
      }
      if (!error.code) {
        if (Object.prototype.hasOwnProperty.call(errorMap, error.message)) {
          message = errorMap[error.message];
        }
      }

      // HTTP 状态码
      const status = error.code;
      console.log(status, "status");

      switch (status) {
        case 401:
          message = "登录失效，请重新登录";
          router.push("/login");
          // 这里可以触发退出的 action
          break;
        case 403:
          message = "拒绝访问";
          break;
        case 404:
          message = "请求地址错误";
          break;
      }
      let responseCode = error.response.status;
      if (responseCode == 401) {
        switch (responseCode) {
          case 401:
            message = "登录失效，请重新登录";
            router.push("/login");
            // 这里可以触发退出的 action
            break;
          case 403:
            message = "拒绝访问";
            break;
          case 404:
            message = "请求地址错误";
            break;
        }
      }
      ElMessage({
        type: "error",
        message: message,
      });
      if (error.code == 402) {
        router.push("/login");
      }
      return Promise.reject(message);
    });
};
export default callApi;
